package com_.dxy_test_.volatile_;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证volatile关键字不能保证原子性的问题
 */
public class VolatileTest {

    private static volatile int num = 0;

    public static void increase(){
        num ++;
    }

    //解决方案一：加锁
//    public synchronized static void increase(){
//        num ++;
//    }

    //解决方案二：使用原子类CAS操作
    private static AtomicInteger ai = new AtomicInteger(0);

    public static void atomicIncrease(){
        ai.getAndIncrement();
    }


    public static void main(String[] args) throws InterruptedException {
        //1、创建10个线程
        Thread[] threads = new Thread[10];

        for (int i = 0; i < 10; i++) {
            //十个线程都调用普通方法
            threads[i] = new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    //num ++ 操作执行1000次
//                    increase();
                    atomicIncrease();
                }
            });
            threads[i].start();
        }

        //等待所有线程执行完成  才继续执行下面的代码
        for (Thread thread : threads) {
            thread.join();
        }

//        System.out.println(num);
        System.out.println(ai.get());
    }
}
